<?php
class JEmployeeSelector extends CInputWidget {

	public $tag;

	public $relatedProjectName;

	public $linkProjectSelectorId;

	public function init(){
		parent::init();
		$cs=Yii::app()->clientScript;
		$script=
		<<<EOF
$.fn.employeeLinkProjectSelect = function(projectSelector){
	var employeeSelector=this;
	var initValue=this.val();
	projectSelector.change(function(){
		var selectedProjectName=$('option:selected',projectSelector)[0].label;
		employeeSelector.employeeFilterProject(selectedProjectName,initValue);
	});
}

$.fn.employeeFilterProject=function(selectedProjectName, initValue){
	var excludeName='当前';
	$("optgroup", this).each(function(){
			if(this.label!=selectedProjectName && this.label!=excludeName){
				//this.disabled='disabled';
			}else{
				if(!initValue){
					$(this).children('option')[0].selected='selected';
				}
			}
		});
}

EOF;

		$cs->registerScript('JEmployeeSelector.init',$script,CClientScript::POS_HEAD);
	}

	public function run() {
		$employeeModel = Employee::model();
		$employees=$employeeModel->cache(20)
		->findAll(
			array(
				'condition' => 'tags.`key`=:key AND ' . $employeeModel->getTableAlias() . '.employed=1',
				'params' => array(
					':key' => $this->tag,
				),
				'with' => array('tags', 'currentProject'),
				'together' => true
			));
		$listData=array();
		$optionData=array();
		$currentEmployeeId=CHtml::resolveValue($this->model,$this->attribute);
		if(!$this->model->isNewRecord && $currentEmployeeId>0 ){
			$currentEmployee=Employee::model()->findByPk($currentEmployeeId);
			$listData['当前']=array(
				$currentEmployee->id=>$currentEmployee->fullName
			);
		}
		if($this->relatedProjectName){
			$listData[$this->relatedProjectName]=array();
		}
		foreach ($employees as $employee){
			if($currentEmployeeId==$employee->id){
				continue;
			}
			if($employee->currentProjectId>0){
				$currentProject=$employee->currentProject;
				if(!isset($listData[$currentProject->name])){
					$listData[$currentProject->name]=array();
				}
				$listData[$currentProject->name][$employee->id]=$employee->fullName;
			}else{
				if(!isset($listData['其它'])){
					$listData['其它']=array();
				}
				$listData['其它'][$employee->id]=$employee->fullName;
			}
		}
		echo CHtml::activeDropDownList($this->model, $this->attribute,
			$listData,array(
				'empty'=>''
			)//array('options'=>array($currentEmployeeId=>array('erp-current-project-id'=>324)))
		);
		if($this->linkProjectSelectorId){
			list($name,$id) = $this->resolveNameID();
			$cs=Yii::app()->clientScript;
			$script=
			<<<EOF
$('#$id').employeeLinkProjectSelect($('#{$this->linkProjectSelectorId}'));
EOF;
			$cs->registerScript('JEmployeeSelector.'.$id,$script,CClientScript::POS_READY);
		}
	}

}